package com.huajin.gateway.util;

public class StringToHex {

    public String convertStringToHex(String str) {

        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            hex.append(Integer.toHexString((int) chars[i]));
        }

        return hex.toString();
    }

    public String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    //504F533838383834  POS88884
    public static void main(String[] args) {

        StringToHex strToHex = new StringToHex();
        System.out.println("\n-----ASCII码转换为16进制 -----");
        String str = "e3be2910000100000000000120454f4644464846454641454e45504341434143414341434143414341434143410000200001";
       /* System.out.println("字符串: " + str);
        String hex = strToHex.convertStringToHex(str);
        System.out.println("转换为16进制 : " + hex);*/

//        hex = "1f2cc20b7ca8e3304c4ff9fc4c3768b0917133fcfd0e982925452699e785d7032afebe2f49916b86e5488362d13783e2597f3260beaa515d48848cb7539f687f";
        System.out.println("\n***** 16进制转换为ASCII *****");
//        System.out.println("Hex : " + hex);
        System.out.println("ASCII : " + strToHex.convertHexToString(str));
    }
}